package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs/encrypt"

	"github.com/astaxie/beego/orm"
)

type Service struct {
	Id            string       `orm:"column(id);pk"`
	ServId        string    `orm:"column(serv_id)"`
	ProdId        string    `orm:"column(prod_id)"`
	OrderId       string    `orm:"column(order_id)"`
	Name          string    `orm:"column(name)"`
	Model         string    `orm:"column(model)"`
	Spec          string    `orm:"column(spec)"`
	Address       string    `orm:"column(address);null"`
	Contact       string    `orm:"column(contact);null"`
	Phone         string    `orm:"column(phone);null"`
	Account       string    `orm:"column(account);null"`
	Rtime         time.Time `orm:"column(rtime);type(timestamp without time zone);null"`
	Ftime         time.Time `orm:"column(ftime);type(timestamp without time zone);null"`
	Remark        string    `orm:"column(remark);null"`
	Status        int       `orm:"column(status)"`
	Isdelete      int       `orm:"column(isdelete)"`
	Ctime         time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater       string    `orm:"column(creater);null"`
	Utime         time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater       string    `orm:"column(updater);null"`
	Content       string    `orm:"column(content);null"`
	Expection     string    `orm:"column(expection);null"`
	Reason        string    `orm:"column(reason);null"`
	Resolve       string    `orm:"column(resolve);null"`
	ResolveUser   string    `orm:"column(resolve_user);null"`
	ResolveUserId string    `orm:"column(resolve_user_id);null"`
	Price         float64   `orm:"column(price);null"`
	DiscountPrice float64   `orm:"column(discount_price);null"`
}
type ServiceForm struct {
	Resolve   string `json:"Resolve"`
	Expection string `json:"Expection"`
	Reason    string `json:"Reason"`
	Content   string `json:"Content"`
	ServId    string `json:"ServId"`
}
func (t *Service) TableName() string {
	return "yjk_service"
}

func init() {
	orm.RegisterModel(new(Service))
}

// AddService insert a new Service into database and returns
// last inserted Id on success.
func AddService(m *Service) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetServiceById retrieves Service by Id. Returns error if
// Id doesn't exist
func GetServiceById(id string) (v *Service, err error) {
	o := orm.NewOrm()
	v = &Service{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetServiceByServId(id string) (v *Service, err error) {
	o := orm.NewOrm()
	v = &Service{ServId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}
func GetServicesByServId(id string) ( []Service, error) {
	o := orm.NewOrm()
	var s []Service
	_,err :=o.QueryTable(new(Service)).Filter("ServId",id).OrderBy("Ctime").All(&s)
	return s, err
}

// GetAllService retrieves all Service matches certain condition. Returns empty list if
// no records exist
func GetAllService(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Service))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Service
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateService updates Service by Id and returns error if
// the record to be updated doesn't exist
func UpdateServiceById(m *Service) (err error) {
	o := orm.NewOrm()
	v := Service{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteService deletes Service by Id and returns error if
// the record to be deleted doesn't exist
func DeleteService(id string) (err error) {
	o := orm.NewOrm()
	v := Service{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Service{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func AddServiceByServAndUser(serv *Serv, user *User, form *ServiceForm)  error{
	service := &Service{}
	service.Id = encrypt.GetGuid()
	service.ServId = serv.Id
	service.ProdId = serv.Prod.Id
	service.OrderId = serv.Order.Id
	service.Name = serv.Name + time.Now().Format("2006-01-02") + "售后"
	service.Model = serv.Model
	service.Spec = serv.Spec
	service.Address = serv.Address
	service.Contact = serv.Contact
	service.Phone = serv.Phone
	service.Account = serv.Account
	service.Rtime = time.Now()
	service.Ftime = time.Now()
	service.Remark = serv.Remark
	service.Status,service.Isdelete,service.Ctime,service.Creater,service.Utime,service.Updater=
		1,0,time.Now(),user.Abbr,time.Now(),user.Abbr

	service.Content = form.Content
	service.Expection = form.Expection
	service.Reason = form.Reason
	service.Resolve = form.Resolve
	service.ResolveUser = user.Abbr
	service.ResolveUserId = user.Id
	service.Price = serv.Price
	service.DiscountPrice = serv.DiscountPrice

	o := orm.NewOrm()
	_,err := o.Insert(service)

	return err
}
